<?php
declare (strict_types=1);

namespace app\common\tool\Jpush;
use app\common\model\JpushLog;
use app\common\model\JpushSchedule;
use JPush\Client;
use JPush\Exceptions\APIConnectionException;
use JPush\Exceptions\APIRequestException;
use think\facade\Log;

/**
 * 极光推送
 */
class Jpush {
    private $app_key = '5449d43d5c1d5c509e9d9a50'; //待发送的应用程序(appKey)，只能填一个。
    private $master_secret = '3fb491169f4d9f00da810835'; //主密码
    private $url = "https://api.jpush.cn/v3/push"; //推送的地址

    public function __construct($app_key=null, $master_secret=null,$url=null)
    {
        if ($app_key) $this->app_key = $app_key;
        if ($master_secret) $this->master_secret = $master_secret;
        if ($url) $this->url = $url;
    }

    /**
     * 发送单条消息
     * @param $device_id
     * @param $content
     * @param $extras
     * @param $alias
     * @return array|string
     */
    public function sendSingleNotify($device_id,$content,$extras,$alias)
    {
        $client = new Client($this->app_key,$this->master_secret);
        try{
            $result = $client->push()
                ->setPlatform('all')
                ->addRegistrationId($device_id)
                ->message($content)
                ->iosNotification($content,$extras)
                ->androidNotification($content,$extras)
                ->options(['apns_production' => true])//false开发环境  true正式环境
                ->send();
        } catch (APIConnectionException $e) {
            return $e->getMessage();
        } catch (APIRequestException $e) {
            return $e->getMessage();
        }
        Log::write("Jpush:sendSingleNotify:".json_encode($result));

        if (isset($result['http_code']) && $result['http_code'] == 200) {
            if (isset($result['body']['sendno']) && isset($result['body']['msg_id'])) {
                JpushLog::create([
                    'sendno' => $result['body']['sendno'],
                    'msg_id' => $result['body']['msg_id'],
                    'push_type' => 'timing',
                    'receiver' => $alias,
                    'content' => $content,
                    'platform' => 'all'
                ]);
            }
        }
        return $result;
    }

    /**
     * 发送全部消息
     * @param $content
     * @param $extras
     * @return array|string
     */
    public function sendAllNotify($content,$extras)
    {
        $client = new Client($this->app_key,$this->master_secret);
        try{
            $result = $client->push()
                ->setPlatform('all')
                ->addAllAudience()
                ->message($content)
                ->iosNotification($content,$extras)
                ->androidNotification($content,$extras)
                ->options(['apns_production' => (bool)env('jpush.apns_production', false)])//false开发环境  true正式环境
                ->send();
        } catch (APIConnectionException $e) {
            return $e->getMessage();
        } catch (APIRequestException $e) {
            return $e->getMessage();
        }
        Log::write("Jpush:sendAllNotify:".json_encode($result));

        if (isset($result['http_code']) && $result['http_code'] == 200) {
            if (isset($result['body']['sendno']) && isset($result['body']['msg_id'])) {
                JpushLog::create([
                    'sendno' => $result['body']['sendno'],
                    'msg_id' => $result['body']['msg_id'],
                    'push_type' => 'timing',
                    'receiver' => 'all',
                    'content' => $content,
                    'platform' => 'all'
                ]);
            }
        }
        return $result;
    }


    /**
     * @param $regid
     * @param $content
     * @param $name
     * @param $extras
     * @param $time
     * @param $alias
     * @return array
     */
    public function sendSingleSchedule($regid,$content,$name,$extras,$time,$alias): array
    {
        $client = new \JPush\Client($this->app_key,$this->master_secret);
        $payload = $client->push()
            ->setPlatform("all")
            //->addAlias($alias)
            ->addRegistrationId($regid)
            ->message($content)
            ->iosNotification($content,$extras)
            ->androidNotification($content,$extras)
            ->options(['apns_production' => (bool)env('jpush.apns_production', false)])
            ->build();

        $result = $client->schedule()->createSingleSchedule("$name",$payload,$time);
        Log::write("Jpush:sendSingleNotify:".json_encode($result));

        if (isset($result['http_code']) && $result['http_code'] == 200) {
            JpushSchedule::create([
                'schedule_id' => $result['body']['schedule_id'],
                'schedule_name' => $result['body']['name'],
            ]);

        }

        return $result;
    }

    //--------------------------------------------------------------------------------------------------------------------------------------------------------

}
